package shun.demo.brightness;

import android.app.Activity;
import android.content.ContentResolver;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.view.WindowManager;
import shun.demo.R;

import java.util.Set;

/**
 * Created by chen on 3/18/14.
 */
public class BrightnessActivity extends Activity implements View.OnClickListener {

    private static final int STEP = 10;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.brightness);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.increase:
                try {
                    increaseBrightness();
                } catch (Settings.SettingNotFoundException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.decrease:
                try {
                    decreaseBrightness();
                } catch (Settings.SettingNotFoundException e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    private void increaseBrightness() throws Settings.SettingNotFoundException {
        ContentResolver cr = getContentResolver();
        int brightness = Settings.System.getInt(cr, Settings.System.SCREEN_BRIGHTNESS);
        int mode = Settings.System.getInt(cr, Settings.System.SCREEN_BRIGHTNESS_MODE);

        if (mode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
            Settings.System.putInt(cr, Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
        }
        brightness += STEP;

        if (brightness > 255) {
            brightness = 255;
        }

        Settings.System.putInt(cr, Settings.System.SCREEN_BRIGHTNESS, brightness);

        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.screenBrightness = brightness / 255.0f;
        getWindow().setAttributes(params);

    }

    private void decreaseBrightness() throws Settings.SettingNotFoundException {
        ContentResolver cr = getContentResolver();
        int brightness = Settings.System.getInt(cr, Settings.System.SCREEN_BRIGHTNESS);
        int mode = Settings.System.getInt(cr, Settings.System.SCREEN_BRIGHTNESS_MODE);

        if (mode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
            Settings.System.putInt(cr, Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
        }
        brightness -= STEP;

        if (brightness < 10) {
            brightness = 10;
        }
        Settings.System.putInt(cr, Settings.System.SCREEN_BRIGHTNESS, brightness);

        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.screenBrightness = brightness / 255.0f;
        getWindow().setAttributes(params);
    }
}